package com.whc.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.whc.api.dto.GoodsCreateDto;
import com.whc.api.dto.OrderAndGoodsDto;
import com.whc.api.dto.OrderDto;
import com.whc.goods.domain.dto.GoodsUpdateDto;
import com.whc.goods.domain.entity.Goods;
import com.whc.goods.domain.entity.Photo;
import com.whc.goods.domain.vo.GoodsVo;
import com.whc.goods.mapper.CartMapper;
import com.whc.goods.mapper.GoodsMapper;
import com.whc.goods.mapper.PhotoMapper;
import com.whc.goods.service.GoodsService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private PhotoMapper photoMapper;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<GoodsVo> selectSoldGoods(long userId) {
        List<Goods> goods = goodsMapper.selectSoldGoods(userId);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;

    }
    @Override
    public List<GoodsVo> selectBoughtGoods(long userId) {
        List<Goods> goods = goodsMapper.selectBoughtGoods(userId);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    @Override
    public List<GoodsVo> getCheaperGoods(long userId) {
        List<Goods> goods = goodsMapper.selectCheaperGoods(userId);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    @Override
    public List<GoodsVo> getWorksGoods(long userId) {
        LambdaQueryWrapper<Goods> lw = new LambdaQueryWrapper<Goods>();
        lw.eq(Goods::getUserId,userId);
        lw.eq(Goods::getType,0);
        List<Goods> goods = goodsMapper.selectList(lw);
        if(goods==null)return null;
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    @Override
    public List<GoodsVo> getUnworksGoods(long userId) {
        LambdaQueryWrapper<Goods> lw = new LambdaQueryWrapper<Goods>();
        lw.eq(Goods::getUserId,userId);
        lw.ne(Goods::getType,0);
        List<Goods> goods = goodsMapper.selectList(lw);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }



    @Transactional
    //添加
    public long insertGoods(GoodsCreateDto goodsCreateDto) {
        //创建商品并赋值
        Goods goods=new Goods();
        BeanUtils.copyProperties(goodsCreateDto,goods);
        goods.setCreateTime(LocalDateTime.now());
        goods.setUpdateTime(LocalDateTime.now());
        goods.setUserId(goodsCreateDto.getUserId());
        goods.setWanters(0);

        goods.setLastPrice(goodsCreateDto.getPrice());
        goods.setType(0);

        goodsMapper.insert(goods);
        long goodId =goods.getId();
//        System.out.println("插入了一个商品id是"+goodId);
        return goodId;
    }

    //删除
    public void deleteGoods(Long gid) {
        goodsMapper.deleteById(gid);
    }


    @Override
    public Goods selectGoodsInCart(Long userId, Long goodsId) {
        return cartMapper.selectCartGoods(userId,goodsId);
    }

    @Override
    public void addGoodsToCart(Long userId,Long goodsId) {
        cartMapper.addGoodsToCart(userId,goodsId);
    }

    @Override
    public Long deleteMany(Long userId,List<Long> goodsIds) {
        return cartMapper.deleteMany(userId,goodsIds);
    }

    @Override
    public Long deleteAll(Long userId) {
        return cartMapper.deleteAll(userId);
    }

    @Override
    public List<GoodsVo> selectCartList(Long userId) {
        ArrayList<GoodsVo> goodsVos = new ArrayList<>();
        List<Goods> goods = cartMapper.selectGoods(userId);
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            //查询商品图片数组，从redis或数据库中拿
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    public List<GoodsVo> selectAll() {
//        IPage<Goods> page=new Page<>(1,5);
//        IPage<Goods> pagescount = goodsMapper.selectPage(page, null);
//        List<Goods> records = pagescount.getRecords();
        LambdaQueryWrapper<Goods> lw = new LambdaQueryWrapper<Goods>();
//        lw.eq(Goods::getCategoryName,CategoryName);
        //这里使用模糊查询,锤子
        lw.eq(Goods::getType,0);

        List<Goods> goods = goodsMapper.selectList(lw);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            //查询商品图片数组，从redis或数据库中拿
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
//        PageResult pageResult=new PageResult();
//        pageResult.setRecords(goodsVos);
//        pageResult.setTotal(records.size());
        return goodsVos;
    }

    @Transactional
    public void addGoodsPhotos(List<String> urls,long goodId) {
        for(String url:urls){
            String photoName=url.substring(url.lastIndexOf("/"));
            Photo photo = new Photo();
            photo.setPhotoUrl(url);
            photo.setPhotoName(photoName);
            photo.setGoodId(goodId);
            photoMapper.insert(photo);
        }
    }

    @Override
    public List<String> findPhotosById(long goodId) {
        QueryWrapper<Photo> queryWrapper=new QueryWrapper<>();
        //这里是给数据库中字段的名字
        queryWrapper.eq("good_id",goodId);
        List<Photo> photos = photoMapper.selectList(queryWrapper);
        List<String> urls=new ArrayList<>();
        for(Photo o:photos){
            urls.add(o.getPhotoUrl());
        }
        return urls;

    }

    @Override
    public List<GoodsVo> getAllExcept(long id) {
        QueryWrapper<Goods> queryWrapper=new QueryWrapper<>();
        queryWrapper.ne("user_id",id);
        queryWrapper.eq("type",0);
        List<Goods> goods = goodsMapper.selectList(queryWrapper);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            //查询商品图片数组，从redis或数据库中拿
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    @Override
    public List<GoodsVo> getGoodsByUserId(Long id) {
        QueryWrapper<Goods> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<Goods> goods = goodsMapper.selectList(queryWrapper);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            //查询商品图片数组，从redis或数据库中拿
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    //根据id查询
    public GoodsVo selectById(long id){

        Goods goods = goodsMapper.selectById(id);
        if(goods==null){
            throw new RuntimeException("商品不存在");
        }
        GoodsVo goodsVo=new GoodsVo();
        BeanUtils.copyProperties(goods,goodsVo);
        return goodsVo;
    }

    @Override
    public List<GoodsCreateDto> selectByIds(List<Long> ids) {
        List<Goods> goods = goodsMapper.selectBatchIds(ids);
        List<GoodsCreateDto> goodsCreateDtos = new ArrayList<>();
        if(goods==null||goods.size()==0){
            throw new RuntimeException("商品不存在");
        }
        for(Goods g:goods){
            GoodsCreateDto goodsCreateDto = new GoodsCreateDto();
            BeanUtils.copyProperties(g,goodsCreateDto);
            goodsCreateDtos.add(goodsCreateDto);
        }
        return goodsCreateDtos;
    }

    @Override
    public void deductGoodsByIds(OrderDto orderDto) {

        for(OrderAndGoodsDto orderDetailDTO:orderDto.getDetail()){
            Goods goods = goodsMapper.selectById(orderDetailDTO.getGoodsId());
            if(goods.getReserves()<orderDetailDTO.getNumber()){
                throw new RuntimeException("库存不足！");
            }
            if(goods.getReserves()==orderDetailDTO.getNumber()){
//                goodsMapper.deleteById(orderDetailDTO.getGoodsId()); 改成逻辑删除
                goods.setReserves(0);
                goods.setType(1); //1表示被卖光
                goods.setUpdateTime(LocalDateTime.now());
                goodsMapper.updateById(goods);

            }else{
                //减库存
                goods.setReserves(goods.getReserves()-orderDetailDTO.getNumber());
                goodsMapper.updateById(goods);
            }

        }
    }

    @Override
    public void resetGoodsByIds(OrderDto orderDto) {
        for(OrderAndGoodsDto orderDetailDTO:orderDto.getDetail()){
            Goods goods = goodsMapper.selectById(orderDetailDTO.getGoodsId());
            if(goods.getType()==1){ //该商品无库存，被逻辑删除
                goods.setReserves(orderDetailDTO.getNumber());
                goods.setUpdateTime(LocalDateTime.now());
                goods.setType(0);
                goodsMapper.updateById(goods);
            }else{
                //恢复库存
                goods.setReserves(goods.getReserves()+orderDetailDTO.getNumber());
                goodsMapper.updateById(goods);
            }

        }
    }

    //根据名称查询
    public List<GoodsVo> selectByName(String name){
        Goods good =Goods.builder().goodsName(name).build();
        good.setType(0);
        List<Goods> goods = goodsMapper.selectByCondition(good);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }


    public void updateGoods(GoodsUpdateDto goodsUpdateDto){
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",goodsUpdateDto.getId());
        Goods pregoods = goodsMapper.selectById(goodsUpdateDto.getId());

        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsUpdateDto,goods);
        goods.setLastPrice(pregoods.getPrice());
        goods.setUserId(pregoods.getUserId());
        goods.setUpdateTime(LocalDateTime.now());
        goodsMapper.update(goods,updateWrapper);
    }

    public void addGoodsWanters(long goodId){
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",goodId);

        goodsMapper.addGoodsWanters(goodId);
    }

    @Override
    @Transactional
    public boolean buyGoods(OrderDto orderDto) {
//        User user=userMapper.selectById(orderDto.getCustomerId());
//        Goods goods = goodsMapper.selectById(orderDto.getGoodsId());
//        double price=Double.parseDouble(goods.getPrice());
//        long reserves=Long.parseLong(goods.getReserves());
//        if(user.getMoney()<price){
//            return false;
//        }
//        //减钱
//        userMapper.reduceMoney(user.getId(),price);
//        System.out.println("储量");
//        //该储量
//        if(reserves==1){
//            goods.setType(1);
//            goods.setReserves("0");
//        }else{
//            goods.setReserves(String.valueOf(reserves-1));
//        }
//        //加订单
//        Orders orders = new Orders();
//        BeanUtils.copyProperties(orderDto,orders);
//        orders.setType(1);
//        orders.setCreateTime(LocalDateTime.now());
//        ordersMapper.insert(orders);
//        goodsMapper.updateById(goods);
        return true;
    }

    //根据分类查询物品
    public List<GoodsVo> SelectGoodsByType(String CategoryName) {
        LambdaQueryWrapper<Goods> lw = new LambdaQueryWrapper<Goods>();
//        lw.eq(Goods::getCategoryName,CategoryName);
        //这里使用模糊查询,锤子
        lw.eq(Goods::getCategoryName,CategoryName);
        lw.eq(Goods::getType,0);
        List<Goods> goods = goodsMapper.selectList(lw);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;
    }

    @Override
    public List<GoodsVo> SelectGoodsByTypeExcept(String categoryName, Long id) {
        LambdaQueryWrapper<Goods> lw = new LambdaQueryWrapper<Goods>();
//        lw.eq(Goods::getCategoryName,CategoryName);
        //这里使用模糊查询,锤子
        lw.eq(Goods::getCategoryName,categoryName);
        lw.eq(Goods::getType,0);
        lw.ne(Goods::getUserId,id);
        List<Goods> goods = goodsMapper.selectList(lw);
        List<GoodsVo> goodsVos=new ArrayList<>();
        for(Goods g : goods){
            GoodsVo gv = new GoodsVo();
            BeanUtils.copyProperties(g,gv);
            gv.setGoodsPhotoUrl(getUrls(g.getId()));
            goodsVos.add(gv);
        }
        return goodsVos;

    }

    public List<String> getUrls(long gid){
        //查询商品图片数组，从redis或数据库中拿
        List<String> photos = findPhotosById(gid);
        return photos;

    }

}
